package com.wlyuan.open.scanner.application.handler.incr;

import com.wlyuan.open.dto.OpenConsigneeSyncDTO;
import com.wlyuan.open.scanner.application.async.AsyncOrderThreadUtils;
import com.wlyuan.open.scanner.application.task.consignee.ConsigneeTaskHandler;
import com.wlyuan.open.scanner.assembler.ScannerConsigneeAssembler;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.repository.ConsigneeRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;

/**
 * @author lijing
 * @description 收货方 增量 listener
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ConsigneeIncrHandler extends BaseIncrHandler<OpenConsigneeSyncDTO> {
    private final ConsigneeRepository consigneeRepository;
    private final ConsigneeTaskHandler consigneeTaskHandler;

    @Override
    public OpenConsigneeSyncDTO process(Long consigneeId) {
        logger.info("收货方增量同步：{}", consigneeId);
        return Optional.ofNullable(consigneeId).map(id -> {
            var consignee = consigneeRepository.getById(id);
            return ScannerConsigneeAssembler.assemble(consignee);
        }).orElse(null);

    }

    @Override
    public void incrByTenantId(Long tenantId) {
        consigneeTaskHandler.handler(tenantId);
    }

    @Override
    public void incrByTime(Long tenantId, String startTime, String endTime) {
        var list = tenantId == null ? consigneeRepository.getByTime(startTime, endTime) : consigneeRepository.getByTenantIdTime(tenantId, startTime, endTime);
        if (CollectionUtils.isEmpty(list)) {
            logger.info("根据时间{},{}数据为0", startTime, endTime);
            return;
        }
        logger.info("根据时间{},{}数据为：{}", startTime, endTime, list.size());
        var partitionList = ListUtils.partition(list, Constants.PAGE_SIZE);
        CountDownLatch countDownLatch = new CountDownLatch(partitionList.size());
        for (List<Long> partition : partitionList) {
            AsyncOrderThreadUtils.getInstance().excute(new Thread(() -> {
                partition.parallelStream().forEach(id -> increment(id));
                countDownLatch.countDown();
            }));
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {

        }
        logger.info("同步完成");
    }

    @Override
    public String getSyncType() {
        return ScannerCodeEnum.CONSIGNEE.getVal();
    }
}
